﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OAuth.Dapper.Infrastructure.Data;
using OAuth.Dapper.Models;
using Dapper.Contrib.Extensions;
using Lk.Common.Extenstion;
using Lk.Common.Helper;

namespace OAuth.Server.Domain
{
    public class UowAccountRepository : IAccountRepository
    {

        private readonly DapperDBContext context;
        public UowAccountRepository(DapperDBContext context)
        {
            this.context = context;
        }

        public async Task<List<Account>> GetAccounts()
        {
            var result = await context.QueryAsync<Account>("SELECT * FROM account").ConfigureAwait(false);
            return result.ToList();
        }

        public async Task<Account> GetAccountById(int id)
        {
            return await context.GetAsync<Account>(id).ConfigureAwait(false);
        }

        public Task Create(Account model)
        {
            throw new NotImplementedException();
        }

        public async Task<int> Insert(Account model)
        {
            model.PasswordSalt = RandomHelper.CreateToken(8);
            model.Password.EncryptText(model.PasswordSalt);
          return   await context.InsertAsync(model);
        }

        public async Task<Account> Login(string userName, string pwassword)
        {
            var user = await GetAccountByUserNameAsync(userName);
            if (user == null)
            {
                throw new InvalidOperationException("帐号不存在");
            }
            if (!string.Equals(user.Password, pwassword.DecryptText(user.PasswordSalt)))
            {
               
                throw new InvalidOperationException("密码错误");
            }
            return user;
        }

        public async Task<Account> GetAccountByUserNameAsync(string userName)
        {
            var result = await context.QueryFirstOrDefaultAsync<Account>("SELECT * FROM Account WHERE UserName=@userName AND  state=1", new { userName });
            return result;
        }

        public async Task<List<Account>> GetByIdAsync(List<int> ids)
        {
            var result = await context.QueryAsync<Account>("SELECT * FROM [Account] WITH NOLOCK WHERE state=1 AND ID=@ids", new { ids });

            return result.ToList();

        }
    }
}
